//
//  AppDelegate.m
//  customer
//
//  Created by Holothurian on 2018/10/19.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "AppDelegate.h"
#import <WXApi.h>
#import "LoginViewController.h"
#import "HomeViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <JPUSHService.h>
#import "MyOrderDetailViewController.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define sendNotification(key)     [[NSNotificationCenter defaultCenter] postNotificationName:key object:self userInfo:nil];  //发送通知



@interface AppDelegate ()<WXApiDelegate,JPUSHRegisterDelegate>

@property (nonatomic,assign)NSInteger push_type;//推送类型

@property (nonatomic,assign)NSInteger order_type;// 类型

@property (nonatomic,assign)NSInteger order_id;//订单id

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    /*
     商家号：1518255671
     key：us37kna3gyfFlz1zpXWResh2TK2F3fEt
     AppID:wx5d990ac413cb31de
     AppSecret:dd9ffdc7fe99fa52ea94be2d1125eec5
     */
    [WXApi registerApp:WXOpenID];
    [self registerJPushWithOptions:launchOptions];
    if ([NSString userInfoEmpty]) {
        [self registerApp];
    }else{
        [self toHomePage];
    }
    
    AutoWeakSelf
    [QYNetManager sharedManager].ErrorForTokenFailed = ^{
        [NSString removeUserInfo];
        [weakSelf errorLogin];
    };
    [self managerMapService];
    [self initIQKeyboardManager];
    [self.window makeKeyWindow];
    
    return YES;
}


- (void)registerApp{
    
    AutoWeakSelf
    LoginViewController * login = [[LoginViewController alloc]initWithLoginSuccess:^{
        [weakSelf toHomePage];
    }];
    UINavigationController * nc = [[UINavigationController alloc]initWithRootViewController:login];
    nc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor]};
    self.window.rootViewController = nc;
    
}

- (void)managerMapService{
    [AMapServices sharedServices].apiKey = AMapLocationApiKey;
}

//跳转首页
- (void)toHomePage{
    self.homeTabBar = [[MainTabBarController alloc]init];
    [self.window setRootViewController:self.homeTabBar];
}



- (void)errorLogin{
    AutoWeakSelf
    LoginViewController * regis = [[LoginViewController alloc]initWithLoginSuccess:^{
        [weakSelf toHomePage];
    }];
    UINavigationController * nc = [[UINavigationController alloc]initWithRootViewController:regis];
    nc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor]};
    self.window.rootViewController = nc;
}

- (void)initIQKeyboardManager{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
}

- (void)registerJPushWithOptions:(NSDictionary *)launchOptions{
    // 3.0.0及以后版本注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:Jpush_AppKey
                          channel:nil
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            K_UserDefault_Write(registrationID,JPush_ID);
            NSLog(@"registrationID :%@",registrationID);
        }else{
            
        }
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
}




- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    
    NSLog(@"handleOpenURL==>%@",url);
    return  [WXApi handleOpenURL:url delegate:self];
}

//iOS 9+
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    id urlScheme = url.scheme;
    if ([urlScheme isEqualToString:WXOpenID]) {
        // 支付
        if ([url.host isEqualToString:@"pay"]) {
            return [WXApi handleOpenURL:url delegate:[PayStyleUtil getInstance]];
        }
        // 授权
        else if ([url.host isEqualToString:@"oauth"]) {
            return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        }
    }
    return NO;
}

//iOS 9-
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    id urlScheme = url.scheme;
    if ([urlScheme isEqualToString:WXOpenID]) {
        // 支付
        if ([url.host isEqualToString:@"pay"]) {
            return [WXApi handleOpenURL:url delegate:[PayStyleUtil getInstance]];
        }
        // 授权
        else if ([url.host isEqualToString:@"oauth"]) {
            return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        }
    }
    return NO;
}

- (void)applicationWillResignActive:(UIApplication *)application {
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    sendNotification(kRegisterBackgroundNoti);
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
     sendNotification(kRegisterFrontNoti)
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    //取消通知
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationWillTerminate:(UIApplication *)application {
}

// 接收到通知事件
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *msg = [userInfo objectForKey:@"alert"];
    NSDictionary* valueDict = [self hsDictionaryWithJSON:[userInfo objectForKey:@"value"]];
    if ([valueDict isKindOfClass:[NSDictionary class]]) {
        self.push_type = [[valueDict objectForKey:@"type"] integerValue];
        if (self.push_type) {
            self.order_type = [[valueDict objectForKey:@"order_type"] integerValue];
            self.order_id = [[valueDict objectForKey:@"order_id"] integerValue];
            if (self.order_id) {
                if ([NSString userInfoEmpty]) {
                    [self registerApp];
                }else{
                    SHOW_ALERT(@"消息通知",msg,@"取消",@"查看",0);
                }
            }
        }
    }
}


#pragma mark - JPUSHRegisterDelegate
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    // Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    NSString *msg = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
    NSDictionary* valueDict = [self hsDictionaryWithJSON:[userInfo objectForKey:@"value"]];
    if ([valueDict isKindOfClass:[NSDictionary class]]) {
        self.push_type = [[valueDict objectForKey:@"type"] integerValue];
        if (self.push_type) {
            self.order_id = [[valueDict objectForKey:@"order_id"] integerValue];
            self.order_type = [[valueDict objectForKey:@"order_type"] integerValue];
            if (self.order_id) {
                if (application.applicationState == UIApplicationStateActive) {
                    SHOW_ALERT(@"消息通知",msg,@"取消",@"查看",0);
                }else{
                    [self doPush:userInfo];
                }
            }
        }else{
            SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
        }
    }
    
    NSLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    
    
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    /*
     {
     "_j_business" = 1;
     "_j_msgid" = 58546797385694343;
     "_j_uid" = 20065281837;
     aps =     {
     alert = "\U6d4b\U8bd5";
     badge = 5;
     sound = happy;
     };
     value = "{order:158,title:'\U6d4b\U8bd5',type:1}";
     }
     */

    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        NSString *msg = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
        NSDictionary* valueDict = [self hsDictionaryWithJSON:[userInfo objectForKey:@"value"]];
        if ([valueDict isKindOfClass:[NSDictionary class]]) {
            self.push_type = [[valueDict objectForKey:@"type"] integerValue];
            if (self.push_type) {
                self.order_id = [[valueDict objectForKey:@"order_id"] integerValue];
                self.order_type = [[valueDict objectForKey:@"order_type"] integerValue];
                if ([NSString userInfoEmpty]) {
                    [self registerApp];
                }else{
                    if (self.order_id) {
                        SHOW_ALERT(@"消息通知",msg,@"取消",@"查看",188);
                    }
                }
            }
        }else{
            SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
        }
    }
}


- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    completionHandler();
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        completionHandler(UIBackgroundFetchResultNewData);
        NSString *msg = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
        NSDictionary* valueDict = [self hsDictionaryWithJSON:[userInfo objectForKey:@"value"]];
        if ([valueDict isKindOfClass:[NSDictionary class]]) {
            self.push_type = [[valueDict objectForKey:@"type"] integerValue];
            if (self.push_type) {
                self.order_id = [[valueDict objectForKey:@"order_id"] integerValue];
                self.order_type = [[valueDict objectForKey:@"order_type"] integerValue];
                if ([NSString userInfoEmpty]) {
                    [self registerApp];
                }else{
                    if (self.order_id) {
                        [self doPush:userInfo];
                    }
                }
            }
        }else{
            SHOW_ALERT(@"消息通知",msg,@"确定",nil,0);
        }
    }
}
#endif

#ifdef __IPHONE_12_0
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    NSString *title = nil;
    if (notification) {
        title = @"从通知界面直接进入应用";
    }else{
        title = @"从系统设置界面进入应用";
    }
    UIAlertView *test = [[UIAlertView alloc] initWithTitle:title
                                                   message:@"pushSetting"
                                                  delegate:self
                                         cancelButtonTitle:@"yes"
                                         otherButtonTitles:nil, nil];
    [test show];
    
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}
#pragma mark - 推送处理
- (void)doPush:(NSDictionary *)userInfo{
    /*
     order_type               push_type
     一步报修待上门3
     一步报修待确认4
     一步报修已完成5
     1装修预约                 装修预约待支付定金6
     装修预约待支付进度款7
     装修预约待支付尾款8
     2设计预约                装修设计待支付定金6
     装修设计待支付进度款7
     装修设计待支付尾款8
     定制加配                 待支付定金9
     待支付尾款10
     */
    
    
    //界面跳转
    if (self.push_type && self.order_id) {
        if(self.push_type == 3 || self.push_type == 4 ||self.push_type == 5) {
            UITabBarController *nav = (UITabBarController*)self.window.rootViewController;
            MyOrderDetailViewController * vc = [[MyOrderDetailViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.isPush = YES;
            dispatch_time_t delayTime = 0;
            if (!nav) {
                delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
            }
            vc.orderId = [NSString stringWithFormat:@"%ld",self.order_id];
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                
                [((UINavigationController *)nav.selectedViewController) pushViewController:vc animated:YES];
            });
        }else if (self.push_type == 6 || self.push_type == 7 || self.push_type == 8){
            UITabBarController *nav = (UITabBarController*)self.window.rootViewController;
            AppointOrderDetailViewController * vc = [[AppointOrderDetailViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.isPush = YES;
            dispatch_time_t delayTime = 0;
            if (!nav) {
                delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
            }
            vc.order_id = [NSString stringWithFormat:@"%ld",self.order_id];
            vc.selectIndex = 3;//
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [((UINavigationController *)nav.selectedViewController) pushViewController:vc animated:YES];
            });
        }else if (self.push_type == 9 || self.push_type == 10){
            UITabBarController *nav = (UITabBarController*)self.window.rootViewController;
            AppointOrderDetailViewController * vc = [[AppointOrderDetailViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.isPush = YES;
            dispatch_time_t delayTime = 0;
            if (!nav) {
                delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
            }
            vc.order_id = [NSString stringWithFormat:@"%ld",self.order_id];
            vc.selectIndex = 4;//
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [((UINavigationController *)nav.selectedViewController) pushViewController:vc animated:YES];
            });
        }
    }
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1 || alertView.tag == 188) {
        //界面跳转
        if (self.push_type && self.order_id) {
            if(self.push_type == 3 || self.push_type == 4 ||self.push_type == 5) {
                UITabBarController *nav = (UITabBarController*)self.window.rootViewController;
                MyOrderDetailViewController * vc = [[MyOrderDetailViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                vc.isPush = YES;
                dispatch_time_t delayTime = 0;
                if (!nav) {
                    delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
                }
                vc.orderId = [NSString stringWithFormat:@"%ld",self.order_id];
                
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    
                    [((UINavigationController *)nav.selectedViewController) pushViewController:vc animated:YES];
                });
            }else if (self.push_type == 6 || self.push_type == 7 || self.push_type == 8){
                UITabBarController *nav = (UITabBarController*)self.window.rootViewController;
                AppointOrderDetailViewController * vc = [[AppointOrderDetailViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                vc.isPush = YES;
                dispatch_time_t delayTime = 0;
                if (!nav) {
                    delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
                }
                vc.order_id = [NSString stringWithFormat:@"%ld",self.order_id];
                vc.selectIndex = 3;//
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [((UINavigationController *)nav.selectedViewController) pushViewController:vc animated:YES];
                });
            }else if (self.push_type == 9 || self.push_type == 10){
                UITabBarController *nav = (UITabBarController*)self.window.rootViewController;
                AppointOrderDetailViewController * vc = [[AppointOrderDetailViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                vc.isPush = YES;
                dispatch_time_t delayTime = 0;
                if (!nav) {
                    delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
                }
                vc.order_id = [NSString stringWithFormat:@"%ld",self.order_id];
                vc.selectIndex = 4;//
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [((UINavigationController *)nav.selectedViewController) pushViewController:vc animated:YES];
                });
            }
        }
        
    }
}


- (NSDictionary *)hsDictionaryWithJSON:(id)json {
    if (!json || json == (id)kCFNull) return nil;
    NSDictionary *dic = nil;
    NSData *jsonData = nil;
    if ([json isKindOfClass:[NSDictionary class]]) {
        dic = json;
    } else if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }
    if (jsonData) {
        dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
        if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
    }
    return dic;
}


@end

///dfgdgfghjfhgkfkfkhfkh
